<script setup lang="ts">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import {PatientType} from "@/api/patient/types";

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<PatientType>>,
    default: () => null
  }
})


const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const schema = reactive<FormSchema[]>([
  {
    field: 'patient_number',
    label: '病历号',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
    }
  },
  {
    field: 'card_number',
    label: '身份证',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
    }
  },
  {
    field: 'name',
    label: '患者名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'gender',
    label: '患者性别',
    component: 'Select',
    componentProps: {
      options: [
        {label: '男', value: 1},
        {label: '女', value: 2},
      ]
    },
    formItemProps: {
      rules: [required()]
    }
  },
  // {
  //   field: 'age',
  //   label: '患者年龄',
  //   component: 'InputNumber',
  //   formItemProps: {
  //     rules: [required()]
  //   }
  // },
  {
    field: 'position',
    label: '所在位置',
    component: 'Input',
  },
])

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
    setSchema([
      {
        field: 'content',
        path: 'componentProps.defaultHtml',
        value: currentRow.content
      }
    ])
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form @register="formRegister" :schema="schema" />
</template>
